package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	request "zong-go/app/http/requests"
	"zong-go/app/models"
	"zong-go/pkg/auth"
	"zong-go/pkg/config"
	"zong-go/pkg/helper"
	"zong-go/pkg/response"
)

type AuthController struct {
	loginRequest request.AuthLoginRequest
	//logoutRequest request.AuthLogoutRequest
	userModel models.User
}

// Options
func (authController *AuthController) Options(context *gin.Context) {
	context.JSON(http.StatusOK, "Options Request!")
}

// Login 用户登录
func (authController *AuthController) Login(context *gin.Context) {
	if err := context.ShouldBindJSON(&authController.loginRequest); err != nil {
		response.ResponseBadRequest(context)
		return
	}
	if u, err := authController.userModel.GetByUsername(authController.loginRequest.Username); err != nil {
		response.ResponseError(context, "用户不存在")
		return
	} else {
		if ok := u.ComparePassword(authController.loginRequest.Password); !ok {
			response.ResponseError(context, "用户密码错误")
			return
		}
		// 获取 token 并存入 session
		token := auth.GetToken(u)

		response.ResponseSuccess(context, "success", map[string]interface{}{
			"access_token": token,
			"token_type":   "Bearer",
			"expires_in":   int64(helper.StringToInt(config.Get("jwt", "expires")) * 60),
		})
	}
}

// Logout 用户退出
func (authController *AuthController) Logout(context *gin.Context) {
	//if err := context.ShouldBindJSON(&authController.logoutRequest); err != nil {
	//	response.ResponseBadRequest(context)
	//	return
	//}

	// 删除 token 实际是刷新 token 但是不返回
	authorization := context.Request.Header.Get("Authorization")
	auth.FlushToken(strings.Fields(authorization)[1], authController.userModel)

	response.ResponseSuccess(context, "success", map[string]interface{}{})
}

// Refresh 用户刷新token
func (authController *AuthController) Refresh(context *gin.Context) {
	authorization := context.Request.Header.Get("Authorization")
	token := auth.RefreshToken(strings.Fields(authorization)[1], authController.userModel)

	response.ResponseSuccess(context, "success", map[string]interface{}{
		"access_token": token,
		"token_type":   "Bearer",
		"expires_in":   int64(helper.StringToInt(config.Get("jwt", "expires")) * 60),
	})
}
